package com.gxa.k12.auth.service.impl;


import com.gxa.k12.auth.entity.UserEntity;
import com.gxa.k12.auth.mapper.UserMapper;
import com.gxa.k12.auth.service.UserService;
import com.gxa.k12.auth.utils.JsonResult;
import com.gxa.k12.auth.utils.JsonUtils;
import com.gxa.k12.auth.utils.MD5Util;
import com.gxa.k12.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("userService")
@Transactional(rollbackFor = Throwable.class)
public class UserServiceImpl  implements UserService {

    @Autowired
    private  UserService userService;

    @Autowired
     private   UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String LOGIN = "==key==!@#$%^";


    @Override
    public Map<String, String> login(String phone, String smscode) {
        Object code = redisTemplate.opsForValue().get(SmsServiceImpl.LOGIN_SMS + phone);

        if(StringUtils.isEmpty(code)){
            throw new BusinessException("验证码已经失效");
        }
        // 对验证码做校验, 如果不一致则抛出异常
        if(!code.equals(smscode)) {
            throw new BusinessException("验证码不一致，请稍后再试");
        }

        //校验完成, 从mysql数据库中查找用户信息
        UserEntity userEntity1 = new UserEntity();
        userEntity1.setUsername(phone);
        UserEntity user = (UserEntity) userMapper.selectOne(userEntity1);

        //如果用户不存在, 则匿名注册,匿名格式: "用户:"+phone , 并指定用户状态
        if(user==null) {
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername(phone);
//            userEntity.setUsername(password);
            userEntity.setStatus(1);
            int insert = userMapper.insert(userEntity);
        }

        //如果用户存在, 但状态不为1,表示冻结状态, 抛出异常
        if(user.getStatus()!=1) {
            throw new BusinessException("账户已冻结");
        }

        redisTemplate.delete(LOGIN+user.getToken());

        //如果用户存在,获取上次的token,如果不为空移除redis中上一次的登录信息

        //生成token，存储登录信息,利用处理后的UUID
        String token = UUID.randomUUID().toString().replace("-", "");

        //处理登录

        user.setGmtCreate(new Date());
        // 设置ip,设置token,更新mysql
        user.setToken(token);


        int insert = userMapper.insert(user);

        // redis添加token信息和过期时间
        redisTemplate.opsForValue().set(LOGIN+token, JsonUtils.objectToJson(user),30, TimeUnit.MINUTES);
        Map<String, String> result = new HashMap<>();
        result.put("token", token);

        return result;
    }

    @Override
    public Map<String, Object> register(UserEntity userEntity) {
        String encode = MD5Util.encode(userEntity.getPassword());
        String username = userEntity.getUsername();
        //在数据库中查找是否有过此账号
        UserEntity userEntity1 = new UserEntity();
        userEntity1.setUsername(username);
        Object o = userMapper.selectOne(userEntity1);
        if(o!=null){
            throw new BusinessException("此账号已经被注册，请正确输入");
        }
        //否则开始注册
        userEntity.setPassword(encode);

        int insert = userMapper.insert(userEntity);
        HashMap<String, Object> HashMap = new HashMap<>();
        JsonResult jsonResult = new JsonResult();
        if(insert>0){

            jsonResult.setCode("1");
            jsonResult.setMsg("注册成功");
        }
        jsonResult.setCode("0");
        jsonResult.setMsg("注册失败");
        HashMap.put("result",jsonResult);



        return HashMap;
    }

    @Override
    public UserEntity validateToken(String token) throws BusinessException {

        Object o = redisTemplate.opsForValue().get(LOGIN + token);
        if (StringUtils.isEmpty(o)) {
            throw new BusinessException("无效token");
        }

        //要更新失效时间
        redisTemplate.expire(LOGIN + token, 60 * 60 * 2,TimeUnit.SECONDS);
        return JsonUtils.jsonToObject(o.toString(), UserEntity.class);
    }
}